package com.yuhs.zixing.study.multithread.mashibing.t002lock.l001;

import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * Function: 产生了脏读
 * synchronized  可以看到 count 资源
 * 对某个对象加锁
 * synchronized 原子性 也保证了 可见性
 *
 * @Author yuhongsheng
 * @Date: 2023-12-23 18:53:26
 */
@Data
@Slf4j
public class Lock001Synchronized004 {

    /**
     * 账户
     */
    String account;

    /**
     * 余额
     */
    BigDecimal balance;

    @SneakyThrows
    public void setBalance(String account, BigDecimal balance) {
        this.account = account;
        TimeUnit.SECONDS.sleep(1);
        this.balance = balance;
    }


    /**
     * 获取余额
     *
     * @param account
     * @return
     */
    public BigDecimal getBalance(String account) {
        return this.balance;
    }


    /**
     * 产生了脏读
     *
     * @param args
     */
    @SneakyThrows
    public static void main(String[] args) {
        Lock001Synchronized004 lock001Synchronized004 = new Lock001Synchronized004();
        new Thread(() -> lock001Synchronized004.setBalance("张三", new BigDecimal("100"))).start();

        log.atInfo().log("张三 余额 {}", lock001Synchronized004.getBalance("张三"));
    }
}
